package com.xbb.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xbb.entity.Role;
import com.xbb.service.RoleService;
import com.xbb.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    RoleService roleService;

    /**
     * 角色多条件分页查询
     * @param role
     * @param page
     * @param limit
     * @return
     */
    @PostMapping("/getRoleList")
    public Object getRoleList(Role role,
                            @RequestParam(required = false, defaultValue = "1") Integer page,
                            @RequestParam(required = false, defaultValue = "10") Integer limit) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<Role>();
        if (!StringUtils.isEmpty(role.getName())) {
            queryWrapper.like("name", role.getName());
        }
        Page<Role> page1 = new  Page<Role>(page,limit);
        IPage<Role> iPage = roleService.page(page1, queryWrapper);
        List<Role> data = iPage.getRecords();
        long total = iPage.getTotal();
        return new Result(0,"角色列表",total,data);
    }

    /**
     * 添加角色
     * @param role
     * @return
     */
    @PostMapping("/addRole")
    public Object addRole(@Valid Role role){
        boolean save = roleService.save(role);
        if(save) {
            return new Result(0,"添加成功");
        }else {
            return new Result(1,"添加失败");
        }
    }

    /**
     * 编辑角色
     * @param id
     * @param role
     * @return
     */
    @PostMapping("/updateRole")
    public Object updateRole(@RequestParam Integer id, @Valid Role role){
        role.setId(id);
        boolean update = roleService.updateById(role);
        if(update) {
            return new Result(0,"修改成功");
        }else {
            return new Result(1,"修改失败");
        }
    }

    /**
     * 删除角色
     * @param id
     * @return
     */
    @PostMapping("/delRole")
    public Object delRole(@RequestParam Integer id) {
        boolean remove = roleService.removeById(id);
        if(remove) {
            return new Result(0,"删除成功");
        }else {
            return new Result(1,"删除失败");
        }
    }

    /**
     * 显示系统中所有的角色
     * @return
     */
    @PostMapping("/getAllRoleList")
    public Object getAllRoleList() {
        return roleService.list();
    }


}
